<style scoped>
.login-content {
	position: fixed;
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;
	display: flex;
	align-items: center;
	justify-content: center;
	overflow: hidden;
	background-color: rgba(164, 163, 163, 0.84);
}

.code-input-image {
	display: flex;
}

.code-input {
	border-radius: 5px 0 0 5px;
	margin-left: 4%;
}

.code-input2 {
	background-color: rgba(109, 69, 243, 0.94);
	border: none;
	border-radius: 0 5px 5px 0;
	color: white;
	cursor: progress;
}

.code-input2:hover {
	background-color: #7955ee;
	-webkit-box-shadow: 0px 0px 30px 0px rgb(160, 142, 224);
	-moz-box-shadow: 0px 0px 30px 0px rgb(160, 142, 224);
	box-shadow: 0px 0px 30px 0px rgb(160, 142, 224);
}

.code-input2:active {
	transform: scale(1.05);
}

.code-input3 {
	background-color: rgba(69, 104, 243, 0.94);
	border: none;
	border-radius: 0 5px 5px 0;
	color: white;
	cursor: no-drop;
}

.login-card {
	background-color: #f8f8f8;
	border-radius: 10px;
	box-sizing: border-box;
	padding: 5px;
	box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.1);
}

.card-header {
	text-align: center;
	margin-bottom: 20px;
}

.card-header h1 {
	font-size: 2em;
	color: #333;
	text-shadow: 1px 1px #ddd;
	margin-top: 0px;
}

.form-group {
	margin-bottom: 15px;
}

.form-group label {
	display: block;
	font-size: 1.2em;
	color: #555;
	margin-bottom: 15px;
}

input[type='text'],
input[type='email'],
input[type='password'] {
	box-sizing: border-box;
	padding: 10px;
	border-radius: 5px;
	border: none;
	width: 100%;
	background-color: #f0f0f0;
	font-size: 1.2em;
	color: #555;
	box-shadow: inset 0px 2px 5px rgba(0, 0, 0, 0.1);
	transition: box-shadow 0.3s ease;
}

input[type='text']:focus,
input[type='email']:focus,
input[type='password']:focus {
	box-shadow: inset 0px 2px 5px rgba(0, 0, 0, 0.3);
	outline: none;
}

.card-close {
	position: relative;
	width: 25px;
	height: 25px;
	border-radius: 50%;
	background-color: rgba(114, 74, 155, 0.15);
	color: white;
	cursor: pointer;
}

.card-close:hover {
	background-color: rgba(161, 127, 255, 0.87);
	transform: scale(1.01);
}

.card-close:active {
	transform: scale(0.9);
}

.login-button {
	background-color: #029d05;
	border: none;
	border-radius: 5px;
	color: #fff;
	cursor: pointer;
	font-size: 1.2em;
	margin-bottom: 5px;
	margin-top: 40px;
	width: 100%;
	transition: background-color 0.3s ease;
	transition: 0.25s;
}

.login-button2 {
	background-color: #007bff;
	border: none;
	border-radius: 5px;
	color: #fff;
	cursor: pointer;
	font-size: 1.2em;
	margin-top: 15px;
	width: 100%;
	transition: background-color 0.3s ease;
	transition: 0.25s;
}

.login-button:hover {
	background-color: rgba(145, 217, 0, 0.91);
	-webkit-box-shadow: 0px 0px 30px 0px rgba(145, 217, 0, 0.91);
	-moz-box-shadow: 0px 0px 30px 0px rgba(145, 217, 0, 0.91);
	box-shadow: 0px 0px 30px 0px rgba(145, 217, 0, 0.91);
}

.login-button2:hover {
	background-color: #0069d9e7;
	-webkit-box-shadow: 0px 0px 30px 0px rgba(0, 105, 217, 1);
	-moz-box-shadow: 0px 0px 30px 0px rgba(0, 105, 217, 1);
	box-shadow: 0px 0px 30px 0px rgba(0, 105, 217, 1);
}
</style>

<template>
	<div
		v-if="data.loginCard"
		class="login-content z-50">
		<div
			class="w-screen mt-16 h-screen overflow-y-scroll l-scrollbar__wrap--hidden-default flex justify-center items-center">
			<div
				:style="data.cardShow === 2 ? 'width: 500px;' : 'width: 450px;'"
				class="login-card">
				<div
					class="cursor-pointer"
					style="width: 60px; height: 60px; position: absolute; transform: rotate(-90deg)"
					@click="getQRcodeFun">
					<el-image
						v-if="data.cardShow !== 2"
						:src="data.qrcodeImage"
						class="w-full h-full hover:scale-105"></el-image>
				</div>
				<!--关闭按钮-->
				<el-icon
					:style="data.cardShow === 2 ? ' margin-left: 460px;' : ' margin-left: 410px;'"
					class="card-close"
					@click="closeLogin()">
					<Close />
				</el-icon>
				<!--标题-->
				<div class="card-header">
					<h1 v-if="data.cardShow === 1">Login</h1>
					<h1 v-else-if="data.cardShow === 2">Register</h1>
					<h1 v-else-if="data.cardShow === 3">Forget</h1>
				</div>
				<div class="card-body mt-4">
					<form>
						<!--用户名 2 -->
						<div
							v-if="data.cardShow === 2"
							class="form-group">
							<!--             <label for="username" >Username</label>-->
							<input
								v-model="data.username"
								placeholder="Username"
								required=""
								type="text" />
						</div>
						<!--手机号1 2 -->
						<div class="form-group">
							<label
								v-if="data.cardShow === 1"
								for="username"
								>Telephone</label
							>
							<input
								v-if="data.cardShow === 1"
								v-model="data.cellPhone"
								required=""
								type="text" />
							<input
								v-if="data.cardShow === 2"
								v-model="data.cellPhone"
								placeholder="cellPhone"
								required=""
								type="text" />
						</div>

						<!--QQ 邮箱 2 3-->
						<div
							v-if="data.cardShow === 2 || data.cardShow === 3"
							class="form-group">
							<label
								v-if="data.cardShow === 3"
								for="password"
								>QQ Mail</label
							>
							<div class="code-input-image">
								<input
									v-if="data.cardShow === 2"
									v-model="data.QQMail"
									placeholder="QQ Mail"
									required=""
									style="width: 70%; border-radius: 5px 0 0 5px"
									type="Email" />
								<input
									v-if="data.cardShow === 3"
									v-model="data.QQMail"
									required=""
									style="width: 70%; border-radius: 5px 0 0 5px"
									type="Email" />
								<input
									v-model="data.QQType"
									class="code-input3"
									required=""
									style="width: 30%"
									type="button" />
							</div>
						</div>

						<!--密码框 1 3-->
						<div
							v-if="data.cardShow === 1 || data.cardShow === 2"
							class="form-group">
							<label
								v-if="data.cardShow === 1"
								for="password"
								>Password</label
							>
							<input
								v-if="data.cardShow === 1"
								v-model="data.password"
								required=""
								type="password" />
							<input
								v-if="data.cardShow === 2"
								v-model="data.password"
								placeholder="Password"
								required=""
								type="password" />
						</div>

						<!--验证码 2 -->
<!--						<div-->
<!--							v-if="data.cardShow === 2"-->
<!--							class="form-group">-->
<!--							<div class="code-input-image">-->
<!--								<el-image-->
<!--									:src="configuration.codeUrl"-->
<!--									alt="加载中...."-->
<!--									style="width: 48%"></el-image>-->
<!--								<input-->
<!--									v-model="data.yzmCode"-->
<!--									class="code-input"-->
<!--									maxlength="5"-->
<!--									placeholder="验证码"-->
<!--									required=""-->
<!--									style="width: 48%"-->
<!--									type="text" />-->
<!--							</div>-->
<!--						</div>-->
						<!--发送短信验证码-->
						<div
							v-if="data.cardShow === 2"
							class="form-group">
							<div class="code-input-image">
								<input
									v-model="data.yzmCode"
									maxlength="5"
									required=""
									style="width: 70%; border-radius: 5px 0 0 5px"
									type="text" />
								<input
									v-model="data.sendCode"
									:disabled="data.disalbe"
									class="code-input2"
									maxlength="5"
									required=""
									style="width: 30%"
									type="button"
									@click="sendSmsCodeFun()" />
							</div>
						</div>
						<!--QQ验证码 3 -->
						<div
							v-if="data.cardShow === 3"
							class="form-group">
							<label for="password">验证码</label>
							<div class="code-input-image">
								<input
									v-model="data.yzmCode"
									maxlength="5"
									required=""
									style="width: 70%; border-radius: 5px 0 0 5px"
									type="text" />
								<input
									v-model="data.sendCode"
									:disabled="data.disalbe"
									class="code-input2"
									maxlength="5"
									required=""
									style="width: 30%"
									type="button"
									@click="sendCodeFun()" />
							</div>
						</div>

						<div class="form-group">
							<div
								v-if="data.cardShow === 1"
								@click="data.cardShow = 3">
								忘记密码？
							</div>
							<div>
								<el-button
									v-if="data.cardShow === 2"
									class="login-button"
									size="large"
									style="margin-top: -0px"
									@click="data.cardShow = 1"
									>返回
								</el-button>
							</div>
							<div>
								<el-button
									v-if="data.cardShow === 1"
									class="login-button"
									size="large"
									@click="data.cardShow = 2"
									>注册
								</el-button>
							</div>
							<div>
								<el-button
									v-if="data.cardShow === 3"
									class="login-button"
									size="large"
									@click="data.cardShow = 1"
									>返回
								</el-button>
							</div>
							<div>
								<el-button
									v-if="data.cardShow === 1"
									class="login-button2"
									size="large"
									@click="commonFun(1)"
									>登录
								</el-button>
							</div>
							<div>
								<el-button
									v-if="data.cardShow === 2"
									class="login-button2"
									size="large"
									@click="commonFun(2)"
									>注册
								</el-button>
							</div>
							<div>
								<el-button
									v-if="data.cardShow === 3"
									class="login-button2"
									size="large"
									@click="commonFun(3)"
									>登录
								</el-button>
							</div>
						</div>
					</form>
				</div>
			</div>
		</div>
	</div>

	<!--扫码登录弹窗-->
	<el-dialog
		v-model="data.qrShow"
		align-center
		title="扫码登录"
		width="400">
		<div class="w-full h-72 bg-base-200/80 flex justify-center items-center">
			<el-image
				:src="data.qrImage"
				class="w-56 h-56"></el-image>
		</div>
		<template #footer>
			<div
				class="cursor-pointer"
				@click="apkShowFun()">
				点击下载app
			</div>
			<div v-if="data.apkShow">
				<apk-page @receive-apk="receiveApk"></apk-page>
			</div>
		</template>
	</el-dialog>
	<div v-if="data.lodingShow">
		<loading></loading>
	</div>
</template>

<script lang="js" setup>
import { onBeforeUnmount, onDeactivated, onMounted, ref, watch } from 'vue'
import { ElNotification } from 'element-plus'
import { configuration } from '../../env.product.js'
import {
	postRegister,
	postLogin,
	postSendEmail,
	postEmailLogin,
	postVerifyCode,
	getQRCode
} from '../interface/UserApi.js'
import { AdressTrans, randomCity } from '../config/MapTrans.js'
import { postDeleteFile } from '../interface/fileApi.js'
import ApkPage from './apkPage.vue'
import { postQueryDict } from '../interface/dictApi.js'
import { sendSmsMessage } from '../interface/ToolApi.js'
const Emit = defineEmits(['receiveLogin']) //定义外部的函数 向外界传值（确定按钮）
let socket = null
const data = ref({
	loginCard: true,
	cardShow: 1, //1是登录 2是注册 3是邮箱登录
	username: '', //用户名
	cellPhone: '', //账号
	mailbox: '', //邮箱
	password: '', //密码
	yzmCode: '', //验证码
	QQMail: '', //QQ邮箱
	QQType: '@qq.com', //qq格式
	disalbe: false, //禁用
	sendCode: '发送验证码', //
	num: 60, //倒计时
	qrShow: false,
	qrImage: '',
	qrcodeImage: '',
	qrName: '',
	ws: configuration.ws, //socket
	apkShow: false,
	lodingShow: false //加载
})


watch(data.value, (newValue, oldValue) => {
	data.value.loginCard = newValue.qrShow !== true
	if (newValue.qrShow === false) {
		closeSoket()
	}
})
/**
 * 页面销毁之前
 */
onBeforeUnmount(() => {
	closeSoket()
})

/**
 * 关闭apk页面
 * @param e
 */
function receiveApk(e) {
	data.value.apkShow = false
}
/**
 * 打开apk页面
 * @param e
 */
function apkShowFun() {
	data.value.apkShow = true
}

/**
 * 加载数据
 */
onMounted(async () => {
	postQueryDictFun()
})

/**
 * 查询字典
 */
function postQueryDictFun() {
	postQueryDict({ id: 13 }).then((res) => {
		if (res.code === 200) {
			data.value.qrcodeImage = configuration.visitFileUrl + res.data[0].dictImage
		}
	})
}
/**
 * 三个共同函数
 */
const commonFun = async (e) => {
	switch (e) {
		case 1:
			//手机号校验
			const regexPhone1 = /^1[3-9]\d{9}$/
			if (!regexPhone1.test(data.value.cellPhone)) {
				ElNotification({ title: 'Error', message: '手机号格式错误', type: 'error' })
				return
			}
			let param1 = {
				cellPhone: data.value.cellPhone,
				password: data.value.password
			}
			loginFun(param1)
			break
		case 2: //注册
			const regexEmail = /^[1-9][0-9]{4,10}(?:\.[0-9]+)?@qq\.com$/
			let QQ = ''
			//QQ邮箱校验
			if (data.value.QQMail.includes('@qq.com')) {
				if (regexEmail.test(data.value.QQMail)) {
					QQ = data.value.QQMail
				} else {
					ElNotification({ title: 'Error', message: 'QQ邮箱格式错误', type: 'error' })
					return
				}
			} else {
				if (regexEmail.test(data.value.QQMail + data.value.QQType)) {
					QQ = data.value.QQMail + data.value.QQType
				} else {
					ElNotification({ title: 'Error', message: 'QQ邮箱格式错误', type: 'error' })
					return
				}
			}
			//手机号校验
			const regexPhone = /^1[3-9]\d{9}$/
			if (!regexPhone.test(data.value.cellPhone)) {
				ElNotification({ title: 'Error', message: '手机号格式错误', type: 'error' })
				return
			}
			//console.log(data.value.password)
			let AdressTransRes = await AdressTrans(randomCity)
			let param2 = {
				userName: data.value.username,
				age: 20,
				cellPhone: data.value.cellPhone,
				password: data.value.password,
				email: QQ,
				address: AdressTransRes.location[0].formatted_address,
				detailedAddress: AdressTransRes.location[0].formatted_address,
				coordinate: AdressTransRes.location[0]
			}
			//校验验证码是否正确
			postVerifyCode({
				code: data.value.yzmCode
			}).then((resCode) => {
				if (resCode.code === 200) {
					//调用注册邮箱接口
					registerFun(param2)
				} else {
					storageFun()
					ElNotification({ title: 'Error', message: '邮箱验证码错误', type: 'error' })
				}
			})
			break
		case 3:
			emailLoginFun()
			break
	}
}
/**
 * 密码登录
 */
const loginFun = async (e) => {
	data.value.lodingShow = true
	postLogin(e).then((res) => {
		if (res.code == 200) {
			localStorage.setItem('token', res.data)
			ElNotification({ title: 'Success', message: '登录成功', type: 'success' })
			receiveLogin([false, JSON.stringify(res.data)])
		} else {
			storageFun()
			ElNotification({ title: 'Error', message: '账号或者密码错误', type: 'error' })
		}
	})
}
/**
 *注册
 */
const registerFun = async (e) => {
	data.value.lodingShow = true
	postRegister(e).then((res) => {
		if (res.code === 200) {
			data.value.cardShow = 1
			ElNotification({ title: 'Success', message: '注册成功', type: 'success' })
			data.value.lodingShow = false
		} else if (res.code=='50000') {
			ElNotification({ title: 'Error', message: '请联系管理员！', type: 'error' })
			storageFun()
		}else {
			ElNotification({ title: 'Error', message: '手机号或邮箱已重复', type: 'error' })
			storageFun()
		}
	})
}
/**
 * 邮箱登录
 */
const emailLoginFun = async () => {
	const regexEmail = /^[1-9][0-9]{4,10}(?:\.[0-9]+)?@qq\.com$/
	let QQ = ''
	//QQ邮箱校验
	if (data.value.QQMail.includes('@qq.com')) {
		if (regexEmail.test(data.value.QQMail)) {
			QQ = data.value.QQMail
		} else {
			ElNotification({ title: 'Error', message: 'QQ邮箱格式错误', type: 'error' })
			return
		}
	} else {
		if (regexEmail.test(data.value.QQMail + data.value.QQType)) {
			QQ = data.value.QQMail + data.value.QQType
		} else {
			ElNotification({ title: 'Error', message: 'QQ邮箱格式错误', type: 'error' })
			return
		}
	}

	let QQMail = QQ
	if (QQMail.length >= 5 && data.value.yzmCode.length >= 5) {
		data.value.lodingShow = true
		postEmailLogin({
			email: QQMail,
			code: data.value.yzmCode
		}).then((res) => {
			if (res.code == 200) {
				localStorage.setItem('token', res.data)
				ElNotification({ title: 'Success', message: '登录成功', type: 'success' })
				receiveLogin([false, JSON.stringify(res.data)])
			} else {
				storageFun()
				ElNotification({ title: 'Error', message: '账号或者验证码错误', type: 'error' })
			}
		})
	}
}
/**
 * 销毁组件（抛出）
 */
const receiveLogin = (e) => {
	data.value.lodingShow = false
	Emit('receiveLogin', e)
}
/**
 * 关闭登录
 */
const closeLogin = () => {
	receiveLogin([false, false])
}
/**
 * 发送短信验证嘛
 */
const sendSmsCodeFun = () =>{
	//手机号校验
	const regexPhone = /^1[3-9]\d{9}$/
	if (!regexPhone.test(data.value.cellPhone)) {
		ElNotification({ title: 'Error', message: '手机号格式错误', type: 'error' })
		return
	}
	if (data.value.disalbe === false) {
		var timeClock = 0
		data.value.disalbe = true
		timeClock = setInterval(function () {
			data.value.num--
			data.value.sendCode = data.value.num + 's重发'
			if (data.value.num === 57) {
				sendSmsMessage({ phone: data.value.cellPhone }).then((res) => {
					if (res.code === 200) {
						ElNotification({ title: 'Success', message: '短信发送成功', type: 'success' })
					} else {
						ElNotification({ title: 'Error', message: res.msg, type: 'error' })
					}
				})
			}
			if (data.value.num === 1) {
				data.value.num = 60
				data.value.sendCode = '重发'
				data.value.disalbe = false
				clearInterval(timeClock)
			}
		}, 1000)
	}


}
/**
 * 发送QQ邮箱验证码
 */
const sendCodeFun = () => {
	const regexEmail = /^[1-9][0-9]{4,10}(?:\.[0-9]+)?@qq\.com$/
	let QQ = ''
	//QQ邮箱校验
	if (data.value.QQMail.includes('@qq.com')) {
		if (regexEmail.test(data.value.QQMail)) {
			QQ = data.value.QQMail
		} else {
			ElNotification({ title: 'Error', message: 'QQ邮箱格式错误', type: 'error' })
			return
		}
	} else {
		if (regexEmail.test(data.value.QQMail + data.value.QQType)) {
			QQ = data.value.QQMail + data.value.QQType
		} else {
			ElNotification({ title: 'Error', message: 'QQ邮箱格式错误', type: 'error' })
			return
		}
	}

	let QQMail = QQ
	if (regexEmail.test(QQMail)) {
		if (data.value.disalbe === false) {
			var timeClock = 0
			data.value.disalbe = true
			timeClock = setInterval(function () {
				data.value.num--
				data.value.sendCode = data.value.num + 's重发'
				if (data.value.num === 57) {
					postSendEmail({ email: QQMail }).then((res) => {
						if (res.code === 200) {
							ElNotification({ title: 'Success', message: '发送成功', type: 'success' })
						} else {
							ElNotification({ title: 'Error', message: '发送失败', type: 'error' })
						}
					})
				}
				if (data.value.num === 1) {
					data.value.num = 60
					data.value.sendCode = '重发'
					data.value.disalbe = false
					clearInterval(timeClock)
				}
			}, 1000)
		}
	}
}
/**
 * 清除缓存
 */
const storageFun = () => {
	localStorage.removeItem('token')
	data.value.lodingShow = false
}
/**
 * 重置数据
 */
const setDataValue = () => {
	;(data.value.username = ''), //用户名
		(data.value.telephon = ''), //账号
		(data.value.mailbox = ''), //邮箱
		(data.value.password = ''), //密码
		(data.value.yzmCode = ''), //验证码
		(data.value.QQMail = ''), //QQ邮箱
		(data.value.QQType = '@qq.com'), //qq格式
		(data.value.disalbe = false), //禁用
		(data.value.sendCode = '发送验证码'), //
		(data.value.num = 60) //倒计时
}
/**
 * 扫码登陆获取二维码
 */
const getQRcodeFun = () => {
	getQRCode().then((res) => {
		if (res.code === 200) {
			data.value.qrImage = res.data.filePath
			data.value.qrName = res.data.qrimg
			data.value.qrShow = true
			openSoket(res.data)
		} else {
			data.value.qrShow = false
			ElNotification({ title: 'Error', message: '获取信息失败！', type: 'error' })
		}
	})
}
/**
 * 连接socket
 */
async function openSoket(param) {
	const socketUrl = data.value.ws + param.uuid
	if (socket != null) {
		socket.close()
		socket = null
	}
	//创建soket
	socket = new WebSocket(socketUrl)
	//打开事件
	socket.onopen = function () {
		//console.log("websocket已打开");
	}
	//监听服务器返回的数据信息
	socket.onmessage = function (msg) {
		//发现消息进入,开始处理前端触发逻辑
		if (msg.data.length >= 20) {
			localStorage.setItem('token', msg.data)
			ElNotification({ title: 'Success', message: '登录成功', type: 'success' })
			data.value.qrShow = false
			closeLogin([false, false])
		}
	}
	//关闭事件
	socket.onclose = function () {
		// console.log("websocket已关闭");
	}
	//发生了错误事件
	socket.onerror = function () {
		console.log('websocket发生了错误')
		closeSoket()
	}
}
/**
 * 关闭sokct
 */
function closeSoket() {
	if (socket !== null) {
		socket.close()
		socket = null
	}
	if (data.value.qrName != null) {
		postDeleteFile({ file: data.value.qrName }).then((res) => {
			data.value.qrName = null
		})
	}
}
</script>
